<?php

namespace App\Http\Controllers\Api;

use App\Http\Requests\api\ReplyRequest;
use App\Models\Reply;
use App\Models\Topic;
use App\Models\User;
use App\Transformers\ReplyTransformer;
use App\Transformers\TopicTransformer;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;

class RepliesController extends Controller
{
    public function store(ReplyRequest $request,Topic $topic, Reply $reply){
        $reply->content = $request->post('content');
        $reply->topic()->associate($topic);
        $reply->user()->associate(Auth::id());
        $reply->save();

        return $this->response->item($reply, new ReplyTransformer())->setStatusCode(201);
    }

    public function destroy(Topic $topic, Reply $reply){
         if($topic->id != $reply->topic_id){
             return $this->response->errorBadRequest();
         }
         $this->authorize('destroy', $reply);
         $reply->delete();

         return $this->response->noContent();
    }

    public function index(Topic $topic){
        $replies = $topic->replies()->paginate(5);

        return $this->response->paginator($replies, new ReplyTransformer());
    }

    public function userIndex(User $user){
        $replies = $user->replies()->paginate(2);

        return $this->response->paginator($replies, new ReplyTransformer());
    }
}
